﻿/*********************************************************************************
**                                                                              **
**  Copyright (C) 2022-2022 LiLong                                              **
**  This file is part of BluetoothCpp.                                          **
**                                                                              **
**  BluetoothCpp is free software: you can redistribute it and/or modify        **
**  it under the terms of the GNU Lesser General Public License as published by **
**  the Free Software Foundation, either version 3 of the License, or           **
**  (at your option) any later version.                                         **
**                                                                              **
**  BluetoothCpp is distributed in the hope that it will be useful,             **
**  but WITHOUT ANY WARRANTY; without even the implied warranty of              **
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               **
**  GNU Lesser General Public License for more details.                         **
**                                                                              **
**  You should have received a copy of the GNU Lesser General Public License    **
**  along with BluetoothCpp.  If not, see <https://www.gnu.org/licenses/>.      **
**********************************************************************************/
#pragma once

#ifdef WIN32

#include <format>
#include <string>
#include <system_error>
#include <windows.h>

inline void throwError(DWORD dwErrorCode)
{
    if (!dwErrorCode)
        return;
    char* psz = nullptr;
    auto ret  = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                              NULL, // （不适用于FORMAT_MESSAGE_FROM_SYSTEM）
                              dwErrorCode,
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              reinterpret_cast<LPSTR>(&psz),
                              0,
                              NULL);
    if (ret > 0)
    {
        auto deleter = [](void* p) { ::HeapFree(::GetProcessHeap(), 0, p); };
        std::unique_ptr<char, decltype(deleter)> ptrBuffer(psz, deleter);
        throw std::runtime_error(ptrBuffer.get());
    }
    else
    {
        throw std::runtime_error(std::format("Unknown error: {}", dwErrorCode));
    }
}
#endif
